<script lang="ts"  setup>
import {ref} from "vue";
import  {userInfoQueryService,userAddService,deleteUser,userRegisterService,alterUserInfoService,findUserInfoService,userStatusAlterService,uploadFileService} from "@/api/system/userInfoQuery.js"
import {ElMessage,UploadFile} from "element-plus";
import { Plus,Delete,Download, ZoomIn,Edit} from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'


//查询条件
const formInline = ref({
  userName: '',
  pageNum:1,
  pageSize:2
})
const formRef = ref(null)
const userInfo = ref({
})
const loading = ref(false);
const imageUrl = ref('')
const statusOptions = ref(["禁用", "正常"]);
//用来显示数据
const tableData = ref([])
const pageNum = ref(1)//当前页
const pageSize = ref(5)//每页条数
const total=ref(20)//总条数
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const dialog = ref({
  title: "",
  visible: false,
});
//重置查询条件
const clearData = () => {
  formInline.value={
    userName:"",
    pageNum:1,
    pageSize:2
  }
}
const onSubmit = async () => {
  formInline.value.pageNum=pageNum.value;
  formInline.value.pageSize=pageSize.value;
  let data =await userInfoQueryService(formInline.value);
  total.value=data.data.total;
  tableData.value=data.data.records;
}

//每页条数发生变化
const handleSizeChange = (val) => {
  onSubmit();
}
//当前页
const handleCurrentChange = (val) => {
  onSubmit();
}

// const handleStatusChange = (row: any) => {
//   alert(row.valid)
// }
const handleStatusChange = async (row: any) => {
  let result= await userStatusAlterService(row.id,row.valid);
  onSubmit();
  ElMessage({
    message: result.message,
    type: 'success',
  })
}
onSubmit();
const findUserInfo = async (id) => {
  userInfo.value=ref({});
  let data =await findUserInfoService(id);
  userInfo.value=data.data;
}
/** 打开标签表单弹窗 */
const openDialog=(row,id) =>{
  dialog.value.visible = true;
  if (row) {
    dialog.value.title = "修改文章";
    findUserInfo(id);
    // getArticleInfo(row.id).then((res) => {
    //   Object.assign(formData, res.data);
    // });
  } else {
    dialog.value.title = "新增文章";
    // Object.assign(formData, null);
  }
}
const deleteUserInfo = async (id) => {
  let result = await deleteUser(id);
  ElMessage({
    message: result.message,
    type: 'success',
  })
  onSubmit();
}
/** 关闭表单弹窗 */
function closeDialog() {
  dialog.value.visible = false;
  imageUrl.value="";
  // userInfo.value.userPic="";
  userInfo.value=ref({});
  // resetForm();
}
const handleSubmit = async () => {
  formRef.value.validate(async (valid) => {
    if (!valid) {
      console.log('验证不通过')
      return false
    }
    if (userInfo.value.id != "" && userInfo.value.id !=null){
      let result= await alterUserInfoService(userInfo.value);
      ElMessage({
        message: result.message,
        type: 'success',
      })
    }else {
      let result= await userAddService(userInfo.value);
      ElMessage({
        message: result.message,
        type: 'success',
      })
    }
    closeDialog();
    onSubmit();
  })

}
//自定义确认密码的校验函数
const rePasswordValid = (rule, value, callback) => {
  if (value == null || value === '') {
    return callback(new Error('请再次确认密码'))
  }
  if (userInfo.value.password !== value) {
    return callback(new Error('两次输入密码不一致'))
  }
  return  callback()
}
//表单校验
const rules={
  userName:[
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 16, message: '用户名必须5到16位之间非空字符', trigger: 'blur' },
  ],
  password:[
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 5, max: 16, message: '密码必须5到16位之间非空字符', trigger: 'blur' },
  ],
  // rePassword:[
  //   // { required: true, message: '请输入用户名', trigger: 'blur' },
  //   // { min: 5, max: 16, message: '用户名必须5到16位之间', trigger: 'blur' },
  //   {validator:rePasswordValid,trigger:'blur'}
  // ]
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}
//上传文件
const uploadSectionFile = async (param: any) => {
  // files.value = param.file;
  var form = new FormData();
  form.append("file", param.file);
  let result = await uploadFileService(form);
  userInfo.value.userPic=result.data;
  loading.value = false;
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('文件格式不正确')
    return false
  } else if (rawFile.size > 1024 * 1024 * 10) {
    ElMessage.error('文件最大不能超过10MB!')
    return false
  }
  loading.value = true;
  return true
}
</script>

<template>
  <el-card class="box-card">
    <div class="card-header">
      <span>用户管理</span>
      <el-button type="primary" @click="openDialog(false)">新增</el-button>
    </div>
    <div>
      <hr>
    </div>
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="用户账号">
        <el-input v-model="formInline.userName" placeholder="用户账号" clearable />
      </el-form-item>
      <el-form-item label="用户名称">
        <el-input v-model="formInline.nickName" placeholder="用户名称" clearable />
      </el-form-item>
      <el-form-item label="用户手机号">
        <el-input v-model="formInline.mobile" placeholder="用户手机号" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <el-button type="primary" @click="clearData">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="userName" label="用户账号" align="center" />
      <el-table-column prop="nickName" label="用户名" align="center" />
      <el-table-column label="用户头像" width="180" align="center">
        <template #default="scope">
          <el-image style="width: 50px;" :src="scope.row.userPic" />
        </template>
      </el-table-column>
      <el-table-column prop="mobile" label="联系电话" align="center"/>
      <el-table-column prop="email" label="邮箱" align="center"/>
      <el-table-column  label="状态" align="center">
        <template #default="scope">
        <el-switch
            v-model="scope.row.valid"
            class="mt-2"
            style="margin-left: 24px"
            inline-prompt
            active-value="1"
            inactive-value="0"
            @change="handleStatusChange(scope.row)"
        />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="center"/>
      <el-table-column prop="updateTime" label="最后修改时间" align="center"/>
      <el-table-column  label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" @click="openDialog(true,scope.row.id)" :icon="Edit" circle />
          <el-button type="danger" @click="deleteUserInfo(scope.row.id)" :icon="Delete" circle />
        </template>

      </el-table-column>
    </el-table>
    <el-pagination
        class="el-p"
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="total,  prev, pager, next, jumper, sizes"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </el-card>
  <el-dialog
      :title="dialog.title"
      @close="closeDialog"
      v-model="dialog.visible"
  >
    <el-form
        ref="formRef"
        :model="userInfo"
        :rules="rules"
        label-width="100px"
        label-position="left"
    >
      <el-form-item prop="userPic"  label="头像" style="height: 178px">
        <el-upload
              v-loading="loading"
              class="avatar-uploader"
              :show-file-list="false"
              name="filedatas"
              action="#"
              :before-upload="beforeAvatarUpload"
              :http-request="uploadSectionFile"
              multiple
          >
            <img v-if="userInfo.userPic" :src="userInfo.userPic" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
      </el-form-item>
      <el-form-item prop="userName" label="用户账号" style="width: 60%">
        <el-input v-model="userInfo.userName" autocomplete="off" ></el-input>
      </el-form-item>
      <el-form-item  prop="password" label="密码" style="width: 60%">
        <el-input v-model="userInfo.password" autocomplete="off" ></el-input>
      </el-form-item>
      <el-form-item prop="nickName" label="用户昵称" style="width: 60%">
        <el-input v-model="userInfo.nickName" autocomplete="off" ></el-input>
      </el-form-item>
      <el-form-item prop="mobile" label="联系电话" style="width: 60%">
        <el-input v-model="userInfo.mobile" autocomplete="off" ></el-input>
      </el-form-item>
      <el-form-item prop="email" label="邮箱" style="width: 60%">
        <el-input v-model="userInfo.email" autocomplete="off" ></el-input>
      </el-form-item>
      <el-form-item prop="valid" label="状态"  style="width: 60%">
        <div>
<!--          <el-radio-->
<!--              v-for="(item, index) in statusOptions"-->
<!--              v-model="userInfo.valid"-->
<!--              :label="item"-->
<!--              :value="index"-->
<!--              :key="index"-->
<!--              border-->
<!--          />-->
          <div>
            <el-radio-group v-model="userInfo.valid">
              <el-radio value="0" size="large" border>禁用</el-radio>
              <el-radio value="1" size="large" border>启用</el-radio>
            </el-radio-group>
          </div>
        </div>
      </el-form-item>

    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>


<style scoped>
.el-p{
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.demo-form-inline .el-select {
  --el-select-width: 220px;
}
.demo-form-inline .el-input {
  --el-input-width: 220px;
}
.card-header{
  display: flex;
  justify-content: space-between;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>